<template>
  <div class="aside_container">
    <div class="toggle-btn" @click="toggleCollapse">|||</div>
    <el-menu class="el-menu-vertical-demo" :collapse="isCollapse" :collapse-transition="false" :default-active="activePath" router unique-opened background-color="#333744" text-color="#fff" active-text-color="#409eff">
      <!-- 一级菜单 -->
      <el-submenu :index="'/' + item.path" v-for="item in menuList" :key="item.id">
        <!-- 一级菜单模板 -->
        <template slot="title">
          <i :class="iconObg[item.id]"></i>
          <span>{{ item.authName }}</span>
        </template>
        <!-- 二级菜单 -->
        <el-menu-item :index="'/' + subItem.path" v-for="subItem in item.children" :key="subItem.id" @click="savaNavState('/' + subItem.path)">
          <!-- 二级菜单模板 -->
          <i class="el-icon-menu"></i>
          <span>{{ subItem.authName }}</span>
        </el-menu-item>
      </el-submenu>
    </el-menu>
  </div>
</template>

<script>
export default {
  name: 'MyAside',
  data() {
    return {
      isCollapse: false,
      menuList: [],
      iconObg: {
        125: 'iconfont icon-user',
        103: 'iconfont icon-tijikongjian',
        101: 'iconfont icon-shangpin',
        102: 'iconfont icon-danju',
        145: 'iconfont icon-baobiao',
      },
      // 被激活的链接地址
      activePath: '',
    }
  },
  created() {
    this.getMenuList()
    // 组件一刷新 自动选定被激活的链接地址
    this.activePath = window.sessionStorage.getItem('activePath')
  },
  methods: {
    async getMenuList() {
      const { data: res } = await this.$http.get('menus')
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.menuList = res.data
    },
    // 侧边栏伸缩
    toggleCollapse() {
      this.isCollapse = !this.isCollapse
      // 自定义事件 传给父一个布尔值
      this.$emit('toggleMenu', this.isCollapse)
    },
    // 菜单被激活 保存菜单的hash地址
    savaNavState(activePath) {
      window.sessionStorage.setItem('activePath', activePath)
      this.activePath = activePath
    },
  },
}
</script>

<style lang="less" scoped>
.el-menu {
  border: 0;
}
.iconfont {
  margin-right: 10px;
}
.toggle-btn {
  background-color: #4a5064;
  color: #fff;
  line-height: 24px;
  font-size: 14px;
  text-align: center;
  cursor: pointer;
  letter-spacing: 0.2em;
}
</style>
